package com.wzt.lianfirecontrol.fragment.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.home.HomeStatisticAdapter;
import com.wzt.lianfirecontrol.bean.EarlyAlarmCountBean;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.FireAlarmCountBean;
import com.wzt.lianfirecontrol.bean.RiskAlarmCountBean;
import com.wzt.lianfirecontrol.bean.StatisticBean;
import com.wzt.lianfirecontrol.bean.SuperviseAlarmCountBean;
import com.wzt.lianfirecontrol.bean.recode.home.ChartsModel2;
import com.wzt.lianfirecontrol.bean.recode.home.HomeTendModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 首页统计
 */
public class HomeStatisticFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private BaseActivity activity;
    private Bundle bundle;

    private View itemContentView;

    private SuperSwipeRefreshLayout swipeRefreshLayout;

    private LinearLayout ll_select_day;
    private TextView tv_select_7;
    private TextView tv_select_30;
    private boolean isSelect7 = true;

    private RecyclerView rlv_list;
    private LinearLayoutManager linearLayoutManager;
    private HomeStatisticAdapter homeStatisticAdapter;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;
    private StatisticBean mStatisticBean;
    private static final int CHART_REQUEST_WHAT = 0;
    /**
     * 表格数据
     */
    private ChartsModel2[] chartsModels = new ChartsModel2[4];


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView) {
            activity = getMyActivity();
            bundle = getArguments();
            itemContentView = inflater.inflate(R.layout.f_statisttic, container, false);
            initView();
            initHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipeRefreshLayout = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipeRefreshLayout);
        swipeRefreshLayout.setOnSwipeRefreshListener(this);
        swipeRefreshLayout.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));

        initListView();

        initListHead();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_data.setBackgroundColor(activity.getResources().getColor(R.color.transparent));
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initListHead() {
        ll_select_day = itemContentView.findViewById(R.id.ll_select_day);
        tv_select_7 = itemContentView.findViewById(R.id.tv_select_7);
        tv_select_7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isSelect7) {
                    isSelect7 = true;
                    ll_select_day.setBackground(activity.getResources().getDrawable(R.mipmap.icon_statistaic_day_7));
                    tv_select_7.setTextColor(activity.getResources().getColor(R.color.white));
                    tv_select_30.setTextColor(activity.getResources().getColor(R.color.main_color));
                    initHttpHelper();
                }

            }
        });
        tv_select_30 = itemContentView.findViewById(R.id.tv_select_30);
        tv_select_30.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelect7) {
                    isSelect7 = false;
                    ll_select_day.setBackground(activity.getResources().getDrawable(R.mipmap.icon_statistaic_day_30));
                    tv_select_7.setTextColor(activity.getResources().getColor(R.color.main_color));
                    tv_select_30.setTextColor(activity.getResources().getColor(R.color.white));
                    initHttpHelper();
                }
            }
        });

        // homeStatisticAdapter.setHeaderView(headView);
    }

    private void initListView() {
        rlv_list = itemContentView.findViewById(R.id.rlv_list);
        linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_list.setLayoutManager(linearLayoutManager);

        homeStatisticAdapter = new HomeStatisticAdapter(activity);
        rlv_list.setAdapter(homeStatisticAdapter);
    }

    /**
     * 获取首页列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)) {
            include_no_net.setVisibility(View.GONE);
        } else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        for (int i = 0; i < 4; i++) {
            chartsModels[i] = null;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ConstData.TIME_FORMAT_YYYY_MM_DD);
        if (isSelect7) {
            long time = date.getTime() - 6 * 24 * 60 * 60 * 1000;
            Date date1 = new Date(time);
            hashMap.put("startTime", simpleDateFormat.format(date1));
            Log.e("startTime", simpleDateFormat.format(date1));
        } else {
            long time = date.getTime() - 29L * 24 * 60 * 60 * 1000;
            Date date1 = new Date(time);
            hashMap.put("startTime", simpleDateFormat.format(date1));
        }

        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new HomeListHttpHelper(activity, Url.CHART_TEND_URL, CHART_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new HomeParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    private class HomeListHttpHelper extends HttpHelper {

        public HomeListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class HomeParseJsonData extends ParseJsonData {


        public HomeParseJsonData() {
        }

        @Override
        public void analyzeResult(String data, Bundle bundle, int what) {
            switch (what) {
                case CHART_REQUEST_WHAT:
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        Gson gson = new Gson();
                        String fireAlarmCount = jsonObject.getString("fireAlarmCount");
                        String riskAlarmCount = jsonObject.getString("riskAlarmCount");
                        String superviseAlarmCount = jsonObject.getString("superviseAlarmCount");
                        String earlyAlarmCount = jsonObject.getString("earlyAlarmCount");
                        //        JSONObject userJson = JSONObject.parseObject(fireAlarmCount);
                        com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(fireAlarmCount);
                        com.alibaba.fastjson.JSONObject jsonObject2 = com.alibaba.fastjson.JSONObject.parseObject(riskAlarmCount);
                        com.alibaba.fastjson.JSONObject jsonObject3 = com.alibaba.fastjson.JSONObject.parseObject(superviseAlarmCount);
                        com.alibaba.fastjson.JSONObject jsonObject4 = com.alibaba.fastjson.JSONObject.parseObject(earlyAlarmCount);
                        FireAlarmCountBean fireAlarmCountBean = JSON.toJavaObject(jsonObject1, FireAlarmCountBean.class);
                        RiskAlarmCountBean riskAlarmCountBean = JSON.toJavaObject(jsonObject2, RiskAlarmCountBean.class);
                        SuperviseAlarmCountBean superviseAlarmCountBean = JSON.toJavaObject(jsonObject3, SuperviseAlarmCountBean.class);
                        EarlyAlarmCountBean earlyAlarmCountBean = JSON.toJavaObject(jsonObject4, EarlyAlarmCountBean.class);
                        Log.e("cccc", fireAlarmCountBean.getCount().getSumCount() + "");
                        Log.e("cccc2", riskAlarmCountBean.getCount().getSumCount() + "");
                        Log.e("cccc3", superviseAlarmCountBean.getCount().getSumCount() + "");
                        Log.e("cccc4",earlyAlarmCountBean.getCount().getSumCount() +"");
                        //               FireAlarmCountBean fireAlarmCountBean = JSONUtil.jsonObjectToBean(new JSONObject(fireAlarmCount), FireAlarmCountBean.class);
                        //
                        //             FireAlarmCountBean fireAlarmCount1 = gson.fromJson(jsonObject.optString("fireAlarmCount"), FireAlarmCountBean.class);
                        //                     Log.e("cccc",fireAlarmCount1.getCount().getSumCount() +"");
                        if (!StringUtils.isEmpty(data)) {
                            LinkedList<HomeTendModel> huoJingModels = (LinkedList<HomeTendModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(jsonObject.getString("fireAlarm")), HomeTendModel.class);
                            //   String fireAlarm = jsonObject.optString("fireAlarm");
//                            FireAlarmCountBean fireAlarmCount = gson.fromJson(jsonObject.optString("fireAlarmCount"), FireAlarmCountBean.class);
//                            String sumCount = fireAlarmCount.getCount().getSumCount();
//                            Log.e("eee",sumCount);

                            //  FireAlarmCountBean fireAlarmCountBean = gson.fromJson(data, FireAlarmCountBean.class);
                            //   FireAlarmCountBean fireAlarmCountBean = gson.fromJson(jsonObject.getString("fireAlarmCount"), FireAlarmCountBean.class);

                            // gson.fromJson(jsonObject.getString("code"), FireAlarmCountBean.class);
                            // Log.e("ee",fireAlarmCountBean.getCount().getSumCount()+"1");
                            LinkedList<HomeTendModel> riskModels =
                                    (LinkedList<HomeTendModel>) JSONUtil.jsonArrayToBeanList(
                                            new JSONArray(jsonObject.getString("riskAlarm")),
                                            HomeTendModel.class);
                            //     EarlyAlarmCountBean riskAlarmCount = (EarlyAlarmCountBean) JSONUtil.jsonArrayToBeanList(new JSONArray(jsonObject.getString("riskAlarmCount")), EarlyAlarmCountBean.class);
                            //   RiskAlarmCountBean riskAlarmCount = gson.fromJson(jsonObject.getString("riskAlarmCount"), RiskAlarmCountBean.class);
                            //   EarlyAlarmCountBean superviseAlarmCount = (EarlyAlarmCountBean) JSONUtil.jsonArrayToBeanList(new JSONArray(jsonObject.getString("superviseAlarmCount")), EarlyAlarmCountBean.class);
                            //   SuperviseAlarmCountBean superviseAlarmCount = gson.fromJson(jsonObject.getString("superviseAlarmCount"), SuperviseAlarmCountBean.class);
                            //   EarlyAlarmCountBean earlyAlarmCount = (EarlyAlarmCountBean) JSONUtil.jsonArrayToBeanList(new JSONArray(jsonObject.getString("earlyAlarmCount")), EarlyAlarmCountBean.class);
                            //    EarlyAlarmCountBean earlyAlarmCount = gson.fromJson(jsonObject.getString("earlyAlarmCount"), EarlyAlarmCountBean.class);
                            LinkedList<HomeTendModel> superviseModels =
                                    (LinkedList<HomeTendModel>) JSONUtil.jsonArrayToBeanList(
                                            new JSONArray(jsonObject.getString("superviseAlarm")),
                                            HomeTendModel.class);
                            LinkedList<HomeTendModel> earlyModels =
                                    (LinkedList<HomeTendModel>) JSONUtil.jsonArrayToBeanList(
                                            new JSONArray(jsonObject.getString("earlyAlarm")),
                                            HomeTendModel.class);
                            bundle.putSerializable("fireAlarmCount", fireAlarmCountBean);
                            bundle.putSerializable("fireAlarm", huoJingModels);
                            bundle.putSerializable("riskAlarmCount",riskAlarmCountBean);
                            bundle.putSerializable("riskAlarm", riskModels);
                            bundle.putSerializable("superviseAlarmCount", superviseAlarmCountBean);
                            bundle.putSerializable("superviseAlarm", superviseModels);
                            bundle.putSerializable("earlyAlarm", earlyModels);
                            bundle.putSerializable("earlyAlarmCount", earlyAlarmCountBean);
                            bundle.putBoolean(REQUEST_OK, true);
                        } else {
                            bundle.putBoolean(REQUEST_OK, false);
                            bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))) {
            // ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            switch (msg.what) {
                case CHART_REQUEST_WHAT:
                    include_progress_bar.setVisibility(View.GONE);
                    if (!isHasData()) {
                        include_no_data.setVisibility(View.VISIBLE);
                    } else {
                        include_no_data.setVisibility(View.GONE);
                    }
                    break;
            }

            return;
        }
        switch (msg.what) {
            case CHART_REQUEST_WHAT:
                setListData(bundle);
                break;

        }
    }

    private void setListData(Bundle msgBundle) {
        LinkedList<HomeTendModel> huoJingModels = (LinkedList<HomeTendModel>) msgBundle.getSerializable("fireAlarm");
        LinkedList<HomeTendModel> riskModels = (LinkedList<HomeTendModel>) msgBundle.getSerializable("riskAlarm");
        LinkedList<HomeTendModel> superviseModels = (LinkedList<HomeTendModel>) msgBundle.getSerializable("superviseAlarm");
        LinkedList<HomeTendModel> earlyModels = (LinkedList<HomeTendModel>) msgBundle.getSerializable("earlyAlarm");
        //  StatisticBean statisticBean = (StatisticBean) msgBundle.getSerializable("statisticBean");
//        StatisticBean.DataBean.FireAlarmCountBean fireAlarmCount = mStatisticBean.getData().getFireAlarmCount();
//        StatisticBean.DataBean.RiskAlarmCountBean riskAlarmCount = mStatisticBean.getData().getRiskAlarmCount();
//        StatisticBean.DataBean.EarlyAlarmCountBean earlyAlarmCount = mStatisticBean.getData().getEarlyAlarmCount();
//        StatisticBean.DataBean.SuperviseAlarmCountBean superviseAlarmCount = mStatisticBean.getData().getSuperviseAlarmCount();
        SuperviseAlarmCountBean superviseAlarmCount = (SuperviseAlarmCountBean) msgBundle.getSerializable("superviseAlarmCount");
        EarlyAlarmCountBean earlyAlarmCount = (EarlyAlarmCountBean) msgBundle.getSerializable("earlyAlarmCount");
        FireAlarmCountBean fireAlarmCount = (FireAlarmCountBean) msgBundle.getSerializable("fireAlarmCount");
        RiskAlarmCountBean riskAlarmCount = (RiskAlarmCountBean) msgBundle.getSerializable("riskAlarmCount");

        for (int i = 0; i < chartsModels.length; i++) {
            if (null == chartsModels[i]) {
                chartsModels[i] = new ChartsModel2();
            }
            switch (i) {
                case 0:
                    //    StatisticBean.DataBean.FireAlarmCountBean fireAlarmCount = mData1.getFireAlarmCount();
                    chartsModels[i].setChartTitle("火警趋势");
                    chartsModels[i].setHomeTendModels(huoJingModels);
                    chartsModels[i].setFireAlarmCount(fireAlarmCount);
                    break;
                case 1:
                    //       StatisticBean.DataBean.EarlyAlarmCountBean earlyAlarmCount = mData1.getEarlyAlarmCount();
                    chartsModels[i].setChartTitle("预警趋势");
                    chartsModels[i].setHomeTendModels(earlyModels);
                    chartsModels[i].setEarlyAlarmCount(earlyAlarmCount);
                    break;
                case 2:
                    //    StatisticBean.DataBean.RiskAlarmCountBean riskAlarmCount = mData1.getRiskAlarmCount();
                    chartsModels[i].setChartTitle("隐患趋势");
                    chartsModels[i].setHomeTendModels(riskModels);
                    chartsModels[i].setRiskAlarmCount(riskAlarmCount);
                    break;
                case 3:
                    //   StatisticBean.DataBean.SuperviseAlarmCountBean superviseAlarmCount = mData1.getSuperviseAlarmCount();
                    chartsModels[i].setChartTitle("监管趋势");
                    chartsModels[i].setHomeTendModels(superviseModels);
                    chartsModels[i].setSuperviseAlarmCount(superviseAlarmCount);
                    break;
            }
        }

        if (isHasData()) {
            include_no_data.setVisibility(View.GONE);
            List<ChartsModel2> chartsModelList = new ArrayList<>();
            for (int i = 0; i < chartsModels.length; i++) {
                if (null != chartsModels[i]) {
                    chartsModelList.add(chartsModels[i]);
                }
            }
            homeStatisticAdapter.clear();
            homeStatisticAdapter.addDatas(chartsModelList);
        } else {
            include_no_data.setVisibility(View.VISIBLE);
        }
        include_progress_bar.setVisibility(View.GONE);
    }


    /**
     * 判断请求是否完成
     *
     * @return
     */
    private boolean isHasData() {
        for (int i = 0; i < chartsModels.length; i++) {
            if (null != chartsModels[i] && null != chartsModels[i].getHomeTendModels()
                    && chartsModels[i].getHomeTendModels().size() > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onSwipeRefresh() {
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {
    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {
    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            updateData();
        }
    }
}
